<template>
  <page-header-wrapper>
    <template v-slot:content>
      <div class="page-header-content">
        <div class="avatar">
          <a-avatar size="large" :src="avatar" />
        </div>
        <div class="content">
          <div class="content-title">
            {{ timeFix }}，{{ nickname }}<span class="welcome-text"></span>
          </div>
          <div> {{ postGroup }} | {{ user.dept.deptName }}</div>
        </div>
      </div>
    </template>
    <template v-slot:extraContent>
    </template>
    <!-- 致谢项目 -->
    <div>
      <a-row :gutter="24">
        <a-col :xl="12" :lg="24" :md="24" :sm="24" :xs="24">
          <a-card class="project-list" style="margin-bottom: 24px;padding: 20px" :bordered="false"
            :body-style="{ padding: 0 }" v-if="isShowContractChat">
            <!-- 导出菜单 -->
            <a-dropdown>
            <a class="ant-dropdown-link" @click.prevent>
              导出合同统计
              <DownOutlined />
            </a>
            <template #overlay>
              <a-menu>
                <a-menu-item>
                  <a
                    @click="ecartsToexcel(leftParam.Header, leftParam.Name, leftParam.Data, leftParam.Title)">导出excel</a>
                </a-menu-item>
                <a-menu-item>
                  <a @click="exportPng(pieChart, '合同统计')">导出图片</a>
                </a-menu-item>
                <!-- <a-menu-item>
                  <a @click="exportChartToPDF('centerLeftcharts', leftParam.Title)">导出pdf</a>
                </a-menu-item> -->
              </a-menu>
            </template>
          </a-dropdown>
            <div ref="pieChart" style="height: 400px;"></div>
          </a-card>
          <!-- 项目简介 -->

        </a-col>
        <a-col style="padding: 0 12px" :xl="12" :lg="24" :md="24" :sm="24" :xs="24">
          <!-- 导航 -->

          <a-card style="margin-bottom: 24px;padding: 20px" :bordered="false" :body-style="{ padding: 0 }" v-if="isShowDeptStaffChat">
            <!-- 导出菜单 -->
            <a-dropdown>
            <a class="ant-dropdown-link" @click.prevent>
              导出部门统计
              <DownOutlined />
            </a>
            <template #overlay>
              <a-menu>
                <a-menu-item>
                  <a
                    @click="ecartsToexcel(rightParam.Header, rightParam.Name, rightParam.Data, rightParam.Title)">导出excel</a>
                </a-menu-item>
                <a-menu-item>
                  <a @click="exportPng(barChart, '部门人员统计')">导出图片</a>
                </a-menu-item>
                <!-- <a-menu-item>
                  <a @click="exportChartToPDF('centerLeftcharts', leftParam.Title)">导出pdf</a>
                </a-menu-item> -->
              </a-menu>
            </template>
          </a-dropdown>

            <div ref="barChart" style="height: 400px;"></div>

          </a-card>

        </a-col>
      </a-row>
    </div>
  </page-header-wrapper>
</template>

<script>
import { timeFix } from '@/utils/util'
import { mapGetters } from 'vuex'
import { PageHeaderWrapper } from '@/components/ProLayout'
import { getUserProfile } from '@/api/system/user'
import { queryDeptStaffCounts } from '@/api/system/staff'
import { queryContractStatusCounts } from '@/api/system/contract'
import * as echarts from 'echarts'
import ExportsEXCL from '@/utils/excelUtils';
export default {
  name: 'Index',
  components: {
    PageHeaderWrapper
  },
  data() {
    return {
      chartData: {
        normal: 0,       // 正常合同
        nearingExpiry: 0, // 即将到期合同
        expired: 0        // 过期合同
      },
      chartData2: {
        departments: ['研发', '测试', '市场营销', '财务', '运维'],
        employees: [33, 15, 13, 4, 7] // 各部门员工数量
      },
      // 贡献者

      noTitleKey: 'RuoYi',
      timeFix: timeFix(),
      // 用户信息
      user: {
        dept: {
          deptName: ''
        }
      },
      roleGroup: {},
      postGroup: {},
      //存储合同图表实例
      pieChart:null,
      //部门员工图表实例
      barChart:null,
      leftParam: {
        Header: [{ value1: '合同' }, { value2: '数量' }, { value3: '百分比' }],
        Name: ['正常合同', '即将到期合同', '过期合同'],
        Data: [],
        Title: '合同类型占比',
      },
      rightParam: {
        Header: [{ value1: '部门' }, { value2: '数量' }, { value3: '百分比' }],
        Name: [],
        Data: [],
        Title: '部门员工占比',
      },
      isShowContractChat: true,
      isShowDeptStaffChat: true
    }
  },
  computed: {
    ...mapGetters([
      'avatar',
      'nickname'
    ])
  },
  created() {
    this.getUser()
    this.contractStatusCounts()
    this.deptStaffCounts()
  },
  mounted() {
    //this.initChart()
    //this.initChart2()
  },
  methods: {

    //导出图表为图片
    exportPng(chartInstance, title = 'chart'){

    let picInfo = chartInstance.getDataURL({
        type: 'png',
        pixelRatio: 1.5, //放大两倍下载，之后压缩到同等大小展示。解决生成图片在移动端模糊问题
        backgroundColor: '#fff',
    }) //获取到的是一串base64信息

    const elink = document.createElement('a')
    elink.download = title
    elink.style.display = 'none'
    elink.href = picInfo
    document.body.appendChild(elink)
    elink.click()
    URL.revokeObjectURL(elink.href) // 释放URL 对象
    },
    ecartsToexcel(header, nameArr, dataArr, title) {
      // 计算百分比
      const percentages = this.calculatePercentage(nameArr, dataArr);
      const arrData = [];
      for (let i = 0; i < nameArr.length; i++) {
        arrData.push({
          value1: nameArr[i],
          value2: dataArr[i],
          value3: percentages[i],
        });
      }

      const excelExporter = new ExportsEXCL(title);
      excelExporter.downLoad({
        header: header,
        body: arrData,
        hasTitle: true,
      });
    },
    calculatePercentage(nameArr, dataArr) {
      // 示例实现
      const total = dataArr.reduce((sum, val) => sum + val, 0);
      return dataArr.map(val => ((val / total) * 100).toFixed(2) + '%');
    },
    contractStatusCounts() {
      queryContractStatusCounts().then(response => {
        const { data } = response

        for (let i = 0; i < data.length; i++) {
          if (data[i].contractStatus === '过期合同'){
            this.chartData.expired = data[i].contractCount
          }else if (data[i].contractStatus === '即将过期合同'){
            this.chartData.nearingExpiry = data[i].contractCount
          }
          if (data[i].contractStatus === '正常合同'){
            this.chartData.normal = data[i].contractCount
          }

        }
        this.initChart()

      })
    },
    deptStaffCounts() {
      queryDeptStaffCounts().then(response => {
        const { data } = response
        let departments = []
        let employees = []
        for (let i = 0; i < data.length; i++) {
          departments.push(data[i].deptName)
          employees.push(data[i].staffCount)
        }
        this.chartData2 = {
          departments,
          employees
        }
        this.initChart2()
      })
    },
    // 获取用户信息
    getUser() {
      getUserProfile().then(response => {
        this.user = response.data
        this.roleGroup = response.roleGroup
        this.postGroup = response.postGroup
      })
    },

    initChart() {
      const chartDom = this.$refs.pieChart

      if (this.chartData.normal === 0 && this.chartData.nearingExpiry === 0 && this.chartData.expired === 0) {
        // 如果没有合同数据，隐藏图表
        // console.log('如果没有合同数据，隐藏图表',this.chartData.expired === 0)
        chartDom.style.display = 'none';
        this.isShowContractChat = false
        return; // 不再继续执行
      }
      this.pieChart = echarts.init(chartDom)

      const option = {
        title: {
          text: '合同状态分布',
          left: 'center'
        },
        tooltip: {
          trigger: 'item'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          data: ['正常合同', '即将到期合同', '过期合同']
        },
        series: [
          {
            name: '合同状态',
            type: 'pie',
            radius: '50%',
            data: [
              { value: this.chartData.normal, name: '正常合同' },
              { value: this.chartData.nearingExpiry, name: '即将过期合同' },
              { value: this.chartData.expired, name: '过期合同' }
            ],
            itemStyle: {
              // 颜色配置
              color: (params) => {
                const colors = ['#4CAF50', '#FF9800', '#F44336'] // 绿色、橙色、红色
                return colors[params.dataIndex]
              }
            },
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      }
      this.leftParam.Data = [
        this.chartData.normal,
        this.chartData.nearingExpiry,
        this.chartData.expired,
      ];
      this.pieChart.setOption(option)
    },

    initChart2() {
      const chartDom = this.$refs.barChart
      if (this.chartData2.employees.every(employee => employee === 0)) {
        // 如果没有任何员工数据，隐藏图表
        chartDom.style.display = 'none';
        this.isShowDeptStaffChat = false
        return; // 不再继续执行
      }
      this.barChart = echarts.init(chartDom)

      const option = {
        title: {
          text: '部门员工数量',
          left: 'center'
        },
        tooltip: {
          trigger: 'item'
        },
        xAxis: {
          type: 'category',
          data: this.chartData2.departments
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '员工数量',
            type: 'bar',
            data: this.chartData2.employees,
            itemStyle: {
              color: () => {
                // 生成随机颜色
                return `rgba(${Math.floor(Math.random() * 256)}, ${Math.floor(Math.random() * 256)}, ${Math.floor(Math.random() * 256)}, 0.8)`
              }
            }
          }
        ]
      }
      this.rightParam.Name = this.chartData2.departments
      this.rightParam.Data = this.chartData2.employees
      this.barChart.setOption(option)
    },
  },
  onSponsorTabChange(key, type) {
    this[type] = key
  }
}

</script>

<style lang="less" scoped>
@import "./index.less";

blockquote {
  padding: 0 1em;
  color: #6a737d;
  border-left: 0.25em solid #dfe2e5;
}

.project-list {

  .card-title {
    font-size: 0;

    a {
      color: rgba(0, 0, 0, 0.85);
      margin-left: 12px;
      line-height: 24px;
      height: 24px;
      display: inline-block;
      vertical-align: top;
      font-size: 14px;

      &:hover {
        color: #1890ff;
      }
    }
  }

  .card-description {
    color: rgba(0, 0, 0, 0.45);
    height: 66px;
    line-height: 22px;
    overflow: hidden;
  }

  .project-item {
    display: flex;
    margin-top: 8px;
    overflow: hidden;
    font-size: 12px;
    height: 20px;
    line-height: 20px;

    a {
      color: rgba(0, 0, 0, 0.45);
      display: inline-block;
      flex: 1 1 0;

      &:hover {
        color: #1890ff;
      }
    }

    .download {
      color: rgba(0, 0, 0, 0.25);
      flex: 0 0 auto;
      float: right;
    }
  }

  .ant-card-meta-description {
    color: rgba(0, 0, 0, 0.45);
    height: 44px;
    line-height: 22px;
    overflow: hidden;
  }
}

.item-group {
  padding: 20px 0 8px 24px;
  font-size: 0;

  a {
    color: rgba(0, 0, 0, 0.65);
    display: inline-block;
    font-size: 14px;
    margin-bottom: 13px;
    width: 25%;
  }
}

.mobile {

  .project-list {

    .project-card-grid {
      width: 100%;
    }
  }

  .more-info {
    border: 0;
    padding-top: 16px;
    margin: 16px 0 16px;
  }

  .headerContent .title .welcome-text {
    display: none;
  }
}
</style>
